<template>
  <div class="root">
    <div class="divBox">
      <div class="content-container">
        <div class="container">
          <div style="width: 390px" class="selectbox-root">
            <a class="selectbox-hint cursor-mi">搜索</a>
            <div class="selectbox-deliver" />
            <input
              class="selectbox-input"
              v-model="searchKeyword"
              placeholder="输入账户名或交易所名称"
              @keyup.enter.native="onClickSearch"
              clearable
            />
          </div>
          <button
            style="margin-left: 16px"
            class="light-green-btn"
            @click="onClickSearch"
          >
            查询
          </button>
          <button
            style="margin-left: 16px"
            class="light-blue-btn"
            @click="onClickOpenAccount"
          >
            +开户
          </button>
          <button
            style="margin-left: 16px; width: 120px"
            class="normal-white-btn"
            @click="onClickBindAccount"
          >
            绑定交易账号
          </button>
        </div>
        <div>
          <el-table
            :header-cell-style="{
              background: '#F2F5F7',
              border: '0px solid #DDDDDD',
              color: '#242B35',
              height: '64px',
            }"
            :show-header="true"
            :data="list"
            :row-style="{ height: '64px' }"
            :cell-style="cellStyle"
            style="width: 100%"
            @row-click="handle"
          >
            <el-table-column min-width="10"></el-table-column>
            <el-table-column label="序号" align="left" min-width="60">
              <template slot-scope="scope"
                ><span>{{ getCurListNo(scope.$index) }}</span></template
              >
            </el-table-column>
            <el-table-column
              prop="accountName"
              label="账号名"
              min-width="100"
            />
            <el-table-column
              prop="carbonExchangeName"
              label="交易所"
              min-width="120"
            />
            <el-table-column
              style="padding-right: 5px"
              prop="createdTime"
              label="开户时间"
              min-width="80"
            />
            <el-table-column
              prop="businessScope"
              label="业务范围"
              min-width="300"
            />
            <el-table-column label="操作" align="center" min-width="50">
              <template slot-scope="scope">
                <a class="list-green-text" @click="readAccout(scope.row)"
                  >查看</a
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div style="margin-top: 30px; margin-bottom: 10px" class="pageBox">
        <div style="flex-grow: 1" />
        <a style="margin: auto" class="pageBox-total-num">共{{ total }}条</a>
        <el-pagination
          style="margin: auto"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-size="pageSize"
          :page-count="pageCount"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import { getTradeAccountList, searchTradeAccountInfo } from "@/api/tradeApi";
import selectDropDownBox from "@/components/selectbox/selectDropDownBox.vue";
import { openUrlInNewWindow } from "@/libs/OpenHelper";
import { cursor } from "@/libs/element-table";
import { setListNo } from "@/libs/public";

export default {
  name: "tradeAccountManager",
  components: { selectDropDownBox },
  data() {
    return {
      searchKeyword: "",
      list: [],
      total: 0,
      current: 1,
      pageCount: 1,
      pageSize: 10,
    };
  },
  methods: {
    cellStyle(data) {
      return cursor(data);
    },
    // 开户
    onClickOpenAccount() {
      this.$router.push({ path: "/trade/account/exchange/" });
    },
    // 绑定交易账号
    onClickBindAccount() {
      this.$router.push({ path: "/account/info/", query: { path: "second" } });
    },
    getCurListNo(index) {
      let curNo = parseInt(index) + 1;
      let size = this.pageSize || 10;
      let page = this.current - 1;
      let no = setListNo(page, size, curNo);
      return no ? no : 1;
    },
    //按关键字搜索交易账号
    onClickSearch() {
      console.log("开始搜索，关键字:", this.searchKeyword);
      
      if (this.searchKeyword === "" || this.searchKeyword.trim() === "") {
        console.log("搜索关键字为空，加载所有数据");
        this.searchKeyword = ""; // 清空搜索关键字
        this.getList(1);
        return;
      }

      let data = {
        asc: true,
        current: 1,
        keyWords: this.searchKeyword,
        size: this.pageSize,
        sortField: "",
      };
      
      console.log("搜索参数:", data);

      searchTradeAccountInfo(data)
        .then((res) => {
          console.log("搜索交易账号结果:", res);
          console.log("响应类型:", typeof res);
          console.log("res.data:", res.data);
          
          // 交易所账户API返回的数据结构
          const responseData = res.data;
          this.list = responseData.records || [];
          this.total = parseInt(responseData.total || 0);
          this.current = 1; // 搜索时重置到第一页
          this.pageCount = Math.ceil(this.total / this.pageSize);
          
          console.log("搜索结果 - 列表长度:", this.list.length);
          console.log("搜索结果 - 总数:", this.total);
          console.log("搜索结果 - 当前页:", this.current);
          
          // 处理数据格式 - 交易所账户数据已经是正确格式，只需要格式化时间
          this.list.map((v) => {
            // 格式化创建时间
            if (v.createdTime) {
              v.createdTime = v.createdTime.split(" ")[0];
            } else {
              v.createdTime = "--";
            }
            // 确保业务范围有默认值
            if (!v.businessScope) {
              v.businessScope = "碳配额交易";
            }
            // 确保碳交易所名称有默认值
            if (!v.carbonExchangeName) {
              v.carbonExchangeName = "碳交易中心";
            }
          });
          
          this.$message.success("查询成功");
        })
        .catch((err) => {
          console.error("搜索交易账号失败:", err);
          // 使用模拟数据进行搜索
          this.searchMockData();
          this.$message.warning("后端API暂时不可用，已使用模拟数据进行搜索演示");
        });
    },
    handle(row) {
      if (row.url) {
        openUrlInNewWindow(row.url);
      } else {
        this.$message.warning("没有对应的url");
      }
    },
    toDetail(url) {
      if (url) {
        openUrlInNewWindow(url);
      } else {
        this.$message.warning("没有对应的url");
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList(this.current);
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getList(this.current);
    },
    // 加载交易账号列表
    getList(page) {
      const data = {
        asc: true,
        current: page,
        size: this.pageSize,
        sortField: "",
        keyWords: this.searchKeyword,
      };
      
      getTradeAccountList(data)
        .then((res) => {
          console.log("获取交易账号列表:", res);
          console.log("响应类型:", typeof res);
          console.log("res.data:", res.data);
          
          // 交易所账户API返回的数据结构
          const responseData = res.data;
          this.list = responseData.records || [];
          this.total = parseInt(responseData.total || 0);
          this.current = parseInt(responseData.current || 1);
          this.pageCount = Math.ceil(this.total / this.pageSize);
          
          // 处理数据格式 - 交易所账户数据已经是正确格式，只需要格式化时间
          this.list.map((v) => {
            // 格式化创建时间
            if (v.createdTime) {
              v.createdTime = v.createdTime.split(" ")[0];
            } else {
              v.createdTime = "--";
            }
            // 确保业务范围有默认值
            if (!v.businessScope) {
              v.businessScope = "碳配额交易";
            }
            // 确保碳交易所名称有默认值
            if (!v.carbonExchangeName) {
              v.carbonExchangeName = "碳交易中心";
            }
          });
        })
        .catch((error) => {
          console.error("获取交易账号列表失败:", error);
          // 使用模拟数据
          this.loadMockData();
          this.$message.warning("后端API暂时不可用，已加载模拟数据进行演示");
        });
    },
    // 加载模拟数据
    loadMockData() {
      const mockData = [
        {
          id: 1,
          accountName: "测试账户001",
          carbonExchangeName: "重庆碳排放权交易中心",
          createdTime: "2022-09-15",
          businessScope: "碳配额交易、CCER交易",
          url: "https://example.com/account/1"
        },
        {
          id: 2,
          accountName: "测试账户002", 
          carbonExchangeName: "北京环境交易所",
          createdTime: "2022-09-20",
          businessScope: "碳配额交易、CCER交易",
          url: "https://example.com/account/2"
        },
        {
          id: 3,
          accountName: "测试账户003",
          carbonExchangeName: "上海环境能源交易所",
          createdTime: "2022-09-25",
          businessScope: "碳配额交易、CCER交易",
          url: "https://example.com/account/3"
        }
      ];
      
      this.list = mockData;
      this.total = mockData.length;
      this.current = 1;
      this.pageCount = 1;
      
      this.$message.info("使用模拟数据展示");
    },
    // 搜索模拟数据
    searchMockData() {
      const allMockData = [
        {
          id: 1,
          accountName: "测试账户001",
          carbonExchangeName: "重庆碳排放权交易中心",
          createdTime: "2022-09-15",
          businessScope: "碳配额交易、CCER交易",
          url: "https://example.com/account/1"
        },
        {
          id: 2,
          accountName: "测试账户002", 
          carbonExchangeName: "北京环境交易所",
          createdTime: "2022-09-20",
          businessScope: "碳配额交易、CCER交易",
          url: "https://example.com/account/2"
        },
        {
          id: 3,
          accountName: "测试账户003",
          carbonExchangeName: "上海环境能源交易所",
          createdTime: "2022-09-25",
          businessScope: "碳配额交易、CCER交易",
          url: "https://example.com/account/3"
        },
        {
          id: 4,
          accountName: "重庆测试账户",
          carbonExchangeName: "重庆碳排放权交易中心",
          createdTime: "2022-09-10",
          businessScope: "碳配额交易、CCER交易",
          url: "https://example.com/account/4"
        },
        {
          id: 5,
          accountName: "北京测试账户",
          carbonExchangeName: "北京环境交易所",
          createdTime: "2022-09-12",
          businessScope: "碳配额交易、CCER交易",
          url: "https://example.com/account/5"
        }
      ];
      
      // 根据搜索关键字过滤数据
      let filteredData = allMockData;
      if (this.searchKeyword) {
        filteredData = allMockData.filter(item => 
          item.accountName.includes(this.searchKeyword) || 
          item.carbonExchangeName.includes(this.searchKeyword)
        );
      }
      
      this.list = filteredData;
      this.total = filteredData.length;
      this.current = 1;
      this.pageCount = Math.ceil(filteredData.length / this.pageSize);
    },
    readAccout(row) {
      console.log("查看交易账号:", row);
      if (row.url) {
        openUrlInNewWindow(row.url);
      } else {
        this.$message.warning("没有对应的url");
      }
    },
  },
  mounted() {
    this.getList(1);
  },
};
</script>
<style lang="scss" scoped>
.root {
  background: #f2f5f7;
}

.divBox {
  margin: 20px;
  background: #ffffff;
  box-shadow: 0px 2px 8px 0px #eaf0f3;
  border-radius: 8px;
}

.container {
  margin: 10px 0px 20px 0px;
  display: flex;
  flex-direction: row;
}

.content-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.cursor-mi {
  cursor: default;
}
</style>